define(["jquery", "bootstrap", "backend", "table", "form"], function (
  $,
  undefined,
  Backend,
  Table,
  Form
) {
  var Controller = {
    index: function () {
      // 初始化表格参数配置
      Table.api.init({
        extend: {
          index_url: "dish/index" + location.search,
          add_url: "dish/add",
          edit_url: "dish/edit",
          qishou_url: "dish/qishou",
          del_url: "dish/del",
          multi_url: "dish/multi",
          import_url: "dish/import",
          table: "dish",
        },
      });

      var table = $("#table");

      // 初始化表格
      // emptyHtml 设置表格空白html
      // formatNoMatches 设置摆个空白文本
      table.bootstrapTable({
        url: $.fn.bootstrapTable.defaults.extend.index_url,
        pk: "id",
        sortName: "id",
        fixedColumns: true,
        fixedRightNumber: 1,
        commonSearch: true,
        search: false,
        searchFormVisible: true,
         showToggle: false,
        showColumns: false,
        showExport: false,
        columns: [
          [
            { checkbox: true },
            { field: "name", title: __("Name"), operate: "LIKE" },
            {
              field: "image",
              title: __("Image"),
              operate: false,
              events: Table.api.events.image,
              formatter: Table.api.formatter.image,
            },
            {
              field: "category.name",
              title: "菜品分类",
              operate: "LIKE",
            },
            { field: "price", title: "售价", operate: false },
            {
              field: "status",
              title: "售卖状态",
              searchList: { 0: __("Status 0"), 1: __("Status 1") },
              formatter: Table.api.formatter.status,
            },
            {
              field: "update_time",
              title: "最后操作时间",
              operate: false,
              addclass: "datetimerange",
              autocomplete: false,
            },
            {
              field: "operate",
              title: __("Operate"),
              table: table,
              events: Table.api.events.operate,
              formatter: Table.api.formatter.operate,
            },
          ],
        ],
      });

      // 为表格绑定事件
      Table.api.bindevent(table);
    },
    add: function () {
      Controller.api.bindevent();
      Controller.dishFlavorConfig();
    },
    edit: function () {
      // Controller.dishFlavorConfig()
      Controller.api.bindevent();
      Controller.dishFlavorConfig();
    },
    api: {
      bindevent: function () {
        Form.api.bindevent($("form[role=form]"));
      },
    },
    dishFlavorConfig: function () {
      var dishConfigBottom = $("#dishConfigBottom");

      // 使用事件委托处理添加按钮点击
      $(document)
        .off("click", "#addDishFlavor")
        .on("click", "#addDishFlavor", function (e) {
          var timestamp = new Date().getTime(); // 使用时间戳保证唯一ID
          var html = `
            <div class="fl-item" data-id="${timestamp}">
                <label class="control-label col-xs-12 col-sm-2"></label>
                <div class="dish-config" style="display: flex;margin-bottom: 10px;">
                    <div style="margin-right: 10px">
                        <input
                            data-rule="required"
                            data-source="dish_flavor/selectpage"
                            class="form-control selectpage"
                            name="row[dish_flavor][${timestamp}][key]"
                            type="text"
                            data-id="${timestamp}"
                            value=""
                        />
                    </div>
                    <div style="flex: 1">
                        <input
                            data-rule="required"
                            data-source="dish_flavor/selectpage"
                            class="form-control selectpage"
                            name="row[dish_flavor][${timestamp}][val][]"
                            type="text"
                            data-id="fl${timestamp}"
                            value=""
                            disabled
                            data-multiple="true"
                        />
                    </div>
                    <a data-id="${timestamp}" style="margin-left: 10px;" href="javascript:;" class="btn btn-danger btn-del btn-disabled" title="删除"><i class="fa fa-trash"></i> 删除</a>
                </div>
            </div>`;
          dishConfigBottom.before(html);
          Controller.api.bindevent();
        });

      // 使用事件委托处理删除按钮
      $(document)
        .off("click", ".btn-del")
        .on("click", ".btn-del", function () {
          $(this).closest(".fl-item").remove();
        });

      // 使用事件委托处理SelectPage联动
      $(document)
        .off("change", ".selectpage")
        .on("change", ".selectpage", function () {
          var $this = $(this);
          var name = $this.val();
          var dataId = $this.data("id");
          var selpage = $(`.selectpage[data-id='fl${dataId}']`);

          if (name.length > 0) {
            if (selpage) {
              selpage.selectPageDisabled(false);
              var selectPageObject = selpage.data("selectPageObject");
              selectPageObject.option.params = { "custom[key]": name };
            }
          } else {
            selpage.selectPageClear();
            selpage.selectPageDisabled(true);
          }
        });
    },
  };

  $.validator.config({
    rules: {
      namerule: function (element) {
        //如果直接返回文本，则表示失败的提示文字
        //如果返回 true 表示成功
        //如果返回 Ajax 对象则表示远程验证
        if (
          !(
            element.value.toString().length > 1 &&
            element.value.toString().length < 21
          ) &&
          !element.value.toString().match(/^[\u4e00-\u9fa5a-zA-Z0-9]+$/)
        ) {
          return "菜品名称输入不符";
        }
        return true;
      },
      pricerul: function (element) {
        //如果直接返回文本，则表示失败的提示文字
        //如果返回 true 表示成功
        //如果返回 Ajax 对象则表示远程验证
        if (
          !(
            element.value.toString().length > 0 &&
            element.value.toString().length < 9
          ) &&
          !element.value.toString().match(/^[-+]?(\d+(\.\d{1,2})?|\.\d{1,2})$/)
        ) {
          return "菜品价格格式有误，请输入大于零且最多保留两位小数的金额";
        }
        return true;
      },
      descrule: function (element) {
        //如果直接返回文本，则表示失败的提示文字
        //如果返回 true 表示成功
        //如果返回 Ajax 对象则表示远程验证
        // console.log("descriptionrule");

        if (
          !(
            element.value.toString().length > -1 &&
            element.value.toString().length < 201
          ) &&
          !element.value.toString().match(/^[\u4e00-\u9fa5a-zA-Z0-9]+$/)
        ) {
          return "菜品描述输入不符，请输入少于200个字";
        }
        return true;
      },
    },
  });

  return Controller;
});
